package com.dwjm.shop.goods;

import com.google.gson.Gson;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/updateGoods")
public class UpdateGoodsHandler extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        try {
            // 读取 JSON 字符串
            BufferedReader reader = req.getReader();
            StringBuilder jsonBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                jsonBuilder.append(line);
            }

            // 反序列化 JSON 为 Goods 对象
            String json = jsonBuilder.toString();
            Gson gson = new Gson();
            Goods goods = gson.fromJson(json, Goods.class);

            // 设置中间人 id（如果你没传）
            if (goods.getMid() == null) {
                goods.setMid(1); // 默认
            }

            // 执行更新
            GoodsDao goodsDao = new GoodsDaoImpl();
            boolean updated = goodsDao.updateGoods(goods);

            Map<String, Object> result = new HashMap<>();
            if (updated) {
                result.put("code", 200);
                result.put("msg", "商品更新成功");
            } else {
                result.put("code", 404);
                result.put("msg", "商品未找到或未更新");
            }
            resp.getWriter().write(gson.toJson(result));
        } catch (Exception e) {
            e.printStackTrace();
            sendError(resp, 500, "服务器内部错误：" + e.getMessage());
        }
    }

    private void sendError(HttpServletResponse resp, int code, String msg) throws IOException {
        Map<String, Object> error = new HashMap<>();
        error.put("code", code);
        error.put("msg", msg);
        resp.setStatus(code);
        resp.getWriter().write(new Gson().toJson(error));
    }
}

